---
slug: 前端路由 #路径，不能重复
title: 前端路由 # 标题
authors: [] # 作者，在authors.yml配置
tags: [facebook, hello, docusaurus] # 标签，在tags.yml配置
toc_min_heading_level: 2 # 最小展示标题
toc_max_heading_level: 5 # 最大展示标题
---


### `HASH`路由

> 改变页面hash`#/xxx`，主页面不会刷新


```html
  <nav>
    <a href="#/index">Home</a>
    <a href="#/product">产品页</a>
    <a href="#/my">我的页</a>
    <div id="container">
    </div>
  </nav>
<script>
  //定义路由表
  let routeList = [
    {
      hash:'index',
      component:'首页'
    },
    {
      hash:'product',
      component:'产品页'
    },
    {
      hash:'my',
      component:'我的'
    }
  ]
  //刚进入页面设置hash为首页
  location.hash='#/';
  const findHash = ()=>{
    console.log(location.hash); //取到的hash为#/my
    let hash =  location.hash.split('#/')[1];
    document.querySelector('#container').innerHTML = routeList.filter(v => v.hash === hash).map(v => v.component);
  }
  //页面路由改变触发事件
  window.onhashchange = findHash;

</script>

```


### history路由
> 运用了H5的`history`api，可以做到不刷新页面

* `back()` 后退一步
* `forward()` 前进一步
* `pushState(null,null,'/')` 去指定地址

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<nav id="navbar">
  <a href="/">Home</a>
  <a href="/about">About</a>
  <a href="/contact">Contact</a>
</nav>
<div id="container"></div>

<script>
  document.querySelector('#navbar').addEventListener('click', e => {
    let target  = e.target;
    if (target.tagName === 'A') {
      e.preventDefault();//阻止a标签跳转的默认事件
      history.pushState({}, "", target.href);//去指定地址
      findHistory();
    }
  })

  //构建路由表
  let historyList = [
    {
      path:'/',
      component:'首页'
    },
    {
      path:'/about',
      component:'about'
    },
    {
      path:'/contact',
      component:'contact'
    }
  ]

  const findHistory = ()=>{
    let pathName =  location.pathname;//获取路由地址
   document.querySelector('#container').innerText = historyList.filter(v=>v.path===pathName).map(v => v.component);
  }

  history.pushState({},null,'/');
  findHistory();

  //对于go,forward,back等方法触发监听，但是对于pushState方法不反应
  window.onpopstate = findHistory;


</script>
</body>

</html>

```